package com.proxy.autoclick.common.util;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

import com.mysql.jdbc.StringUtils;

/**
 * Datasource util
 *
 */
public class DataSourceUtil {
	
	private static DataSource dataSource = null;
	public static boolean DB_STRING_CHANGED = false;
	
	/**
	 * Prepare data source.
	 */
	static{
		if (dataSource == null) {
			initDataSource();
		}
	}
	
	private static void initDataSource()
	{
		try {
			Class.forName(ConfigureString.getDriverClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		BasicDataSource basicDs = new BasicDataSource();
		
		basicDs.setUrl(ConfigureString.getUrl());
		basicDs.setUsername(ConfigureString.getUsername());
		if(!StringUtils.isNullOrEmpty(ConfigureString.getPassword()))
			basicDs.setPassword(ConfigureString.getPassword());
		dataSource =basicDs;
	}
	
	/**
	 * return data source.
	 * @return
	 */
	public static DataSource getDataSource() {
		if(DB_STRING_CHANGED)
		{
			initDataSource();
			DB_STRING_CHANGED = false;
		}
		return dataSource;
	}
	
	/**
	 * Close data source.
	 * @throws SQLException
	 */
	public static void closeDataSource() throws SQLException {
		((BasicDataSource) dataSource).close();
	}

}
